package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author alexis
 * @date 2025-06-09
 */
@Slf4j
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警数据过滤
     */
    @Override
    public void alertFilter() {
        // 1.查询所有报警规则
        Long ruleCount = lambdaQuery().eq(AlertRule::getStatus, 1).count();
        if (ruleCount <= 0) {
            return;
        }

        // 2.查询所有设备上报的数据
        List<Object> allDeviceDataList = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(allDeviceDataList)) {
            return;
        }

        // 3.数据格式标准化处理
        allDeviceDataList.forEach(deviceDataList -> {
            List<DeviceData> list = JSONUtil.toList((String) deviceDataList, DeviceData.class);
            list.forEach(this::alertFilterDeviceData);
        });
    }

    /**
     * 设备数据过滤
     *
     * @param deviceData 设备数据
     * @description 对每一条数据按照报警规则进行过滤
     */
    private void alertFilterDeviceData(DeviceData deviceData) {
        // 1.数据的上报时间超过一分钟，则不处理
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long betweenTime = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (betweenTime > 60) {
            return;
        }

        // 2.查询所有的报警规则
        // 2.1 查询该产品下全部设备对应的报警规则
        List<AlertRule> allDeviceRuleList = lambdaQuery().eq(AlertRule::getStatus, 1)
                                                         .eq(AlertRule::getProductKey, deviceData.getProductKey())
                                                         .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                                                         .eq(AlertRule::getIotId, "-1")
                                                         .list();

        // 2.2 查询该产品下设备对应的所有报警规则
        List<AlertRule> singleDevicelist = lambdaQuery().eq(AlertRule::getStatus, 1)
                                                        .eq(AlertRule::getProductKey, deviceData.getProductKey())
                                                        .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                                                        .eq(AlertRule::getIotId, deviceData.getIotId())
                                                        .list();
        Collection<AlertRule> allRuleList = CollUtil.addAll(allDeviceRuleList, singleDevicelist);
        List<AlertRule> distinctAllRuleList = CollUtil.distinct(allRuleList);


        // 3.遍历规则，进行校验
        if (CollUtil.isEmpty(distinctAllRuleList)) {
            return;
        }
        distinctAllRuleList.forEach(rule -> {
            processDeviceDataWithRule(deviceData, rule);
        });
    }

    /**
     * 报警规则处理
     *
     * @param deviceData 设备数据
     * @param rule       报警规则
     */
    private void processDeviceDataWithRule(DeviceData deviceData, AlertRule rule) {
        // 1.第一层校验：判断是否在生效时间内
        //1.1 获取生效时间
        String effectivePeriod = rule.getAlertEffectivePeriod();
        String[] split = effectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        // 2.获取数据的上报时间
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        // 3.判断数据上报时间是否在生效时间内
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            return;
        }

        // 2.第二层校验：校验数据是否达到阈值
        // 2.1 获取数据阈值
        Double value = rule.getValue();
        // 2.2 校验是否达到阈值
        int compare = Double.compare(Double.parseDouble(deviceData.getDataValue()), value);
        String countKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + deviceData.getProductKey();
        String countHashKey = deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        if ((">=".equals(rule.getOperator()) && compare < 0) || ("<".equals(rule.getOperator()) && compare >= 0)) {
            // 2.3 未达到阈值，删除redis中的报警次数，否则继续后面的校验
            redisTemplate.opsForHash().delete(countKey, countHashKey);
            return;
        }

        // 3.第三层校验：判断数据是否在沉默期
        // 3.1 在redis中获取规则的沉默周期
        String silentKey =
                CacheConstants.ALERT_SILENT_PREFIX + deviceData.getProductKey() + ":" + deviceData.getIotId() +
                ":" + deviceData.getFunctionId() + ":" + rule.getId();
        String silentPeriod = redisTemplate.opsForValue().get(silentKey);
        // 3.2 判断数据是否在沉默期
        if (StringUtils.isNotEmpty(silentPeriod)) {
            return;
        }

        // 4.第四层校验：判断是否等于持续周期
        // 4.1 在redis中查询报警次数
        String count = (String) redisTemplate.opsForHash().get(countKey, countHashKey);
        // 4.2 计算当前报警次数（已报警次数+1）
        int alertCount = StringUtils.isEmpty(count) ? 1 : Integer.parseInt(count) + 1;
        // 4.3 判断是否达到持续周期
        // 4.3.1 未达到持续周期，则更新redis中的报警次数，不做处理
        if (!rule.getDuration().equals(alertCount)) {
            redisTemplate.opsForHash().put(countKey, countHashKey, String.valueOf(alertCount));
            return;
        }
        // 4.3.2 达到持续周期，则进行报警处理
        log.info("触发报警:{}", rule.getAlertRuleName());

        // 5.校验全部通过，触发报警
        // 5.1 删除redis中的报警次数
        redisTemplate.opsForHash().delete(countKey, countHashKey);

        // 5.2 添加redis中的沉默周期
        redisTemplate.opsForValue().set(
                silentKey, String.valueOf(rule.getAlertSilentPeriod()), rule.getAlertSilentPeriod(),
                TimeUnit.MINUTES
                                       );

        // 5.3 根据数据类型寻找对应的处理人员
        List<Long> userIds = new ArrayList<>();
        // 5.3.1 判断是否是老人数据
        if (rule.getAlertDataType().equals(0)) {
            // 5.3.1.1 随身设备，查找对应的护理人员
            if (deviceData.getLocationType().equals(0)) {
                userIds = deviceMapper.selectNursingIdsByIotWithElder(deviceData.getIotId());
            } else if (deviceData.getLocationType().equals(1)) {
                // 5.3.1.2 固定设备，通过床位查询对应的护理人员
                userIds = deviceMapper.selectNursingIdsByIotWithBed(deviceData.getIotId());
            }
        } else {
            // 5.3.2 不是老人数据，直接寻找维修人员
            userIds = sysUserRoleMapper.selectUserIdsByRoleKey("maintainer");
        }
        // 5.3.3 始终都要寻找超级管理员
        List<Long> adminIds = sysUserRoleMapper.selectUserIdsByRoleKey("admin");
        Collection<Long> allUserIds = CollUtil.addAll(userIds, adminIds);
        allUserIds = CollUtil.distinct(allUserIds);

        // 5.4 批量保存报警数据
        List<AlertData> alertDataList = insertBatchAlertData(deviceData, rule, allUserIds);

        // websocket推送消息
        websocketNotify(alertDataList.get(0), rule, allUserIds);
    }

    /**
     * websocket推送消息
     *
     * @param alertData  告警数据
     * @param rule       报警规则
     * @param allUserIds 推送给的userIds
     */
    private void websocketNotify(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        // 属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        // 向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, allUserIds);
    }

    private List<AlertData> insertBatchAlertData(DeviceData deviceData, AlertRule rule, Collection<Long> allUserIds) {
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(rule.getId());
        String alertReason = CharSequenceUtil.format(
                "{}{}{},持续{}个周期就报警", rule.getFunctionName(), rule.getOperator(), rule.getValue(),
                rule.getDuration()
                                                    );
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(rule.getAlertDataType());
        // 遍历userIds
        List<AlertData> alertDataList = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());

        // 批量保存报警数据
        alertDataService.saveBatch(alertDataList);

        return alertDataList;
    }

}
